package com.cheetah.start.system.online.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.constant.SessionConst;
import com.cheetah.start.common.listener.OnLineManager;
import com.cheetah.start.common.query.PageQuery;
import com.cheetah.start.system.admin.domain.SysAdmin;
import com.cheetah.start.system.online.domain.OnLine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("/online")
public class OnLineController extends ResultController {

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @return {@link ResultTable}
     */
    @GetMapping("/list")
    public ResultTable list(PageQuery pageQuery) {
        Map<String, HttpSession> onLineManagerSessions = OnLineManager.getInstance().getSessions();
        List<OnLine> onLines = new ArrayList<>();
        if (CollUtil.isNotEmpty(onLineManagerSessions)) {
            for (Map.Entry<String, HttpSession> sessionEntry : onLineManagerSessions.entrySet()) {
                OnLine onLine = new OnLine();
                onLine.setSessionId(sessionEntry.getKey());
                HttpSession value = sessionEntry.getValue();
                long creationTime = value.getCreationTime();
                onLine.setLoginTime(new Date(creationTime));
                SysAdmin admin = (SysAdmin) value.getAttribute(SessionConst.NAME);
                BeanUtil.copyProperties(admin, onLine);
                onLines.add(onLine);
            }
            List<OnLine> page = CollUtil.page(pageQuery.getPage() - 1, pageQuery.getLimit(), onLines);
            return pageTable(page, onLines.size());
        }
        return pageTable(null, 0);
    }

    /**
     * 退出
     *
     * @param sessionId 会话id
     * @return {@link Result}
     */
    @PostMapping("/exit")
    public Result exit(String sessionId) {
        HttpSession session = OnLineManager.getInstance().getSession(sessionId);
        session.removeAttribute(SessionConst.NAME);
        return success("退出成功");
    }
}
